# 图片验证码
from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response

from django.db.models import Q

import random
import string
from captcha.image import ImageCaptcha
import redis
import jwt
class YanZheng(APIView):
    def get(self,request,uuid):
        # 生成一个随机码

        sui = ''.join(random.sample(string.ascii_letters + string.digits,4))

        print('随机码',sui)

        # 生成一个图片序列
        img = ImageCaptcha()

        # 生成io字节码
        wang = img.generate(sui)

        # 将随机码存入redis
        redisw = redis.Redis(host='localhost',port=6379,password='123321')

        # 存储字节码
        redisw.set(uuid,sui,ex=60 * 5)

        return HttpResponse(wang,content_type='image/png')

    def post(self,request,uuid):
        # 接收前端数据

        wang = request.data.get('验证码')

        # 验证验证码是否相等

        redisw = redis.Redis(host='localhost', port=6379, password='123321')
        deng = redisw.get(uuid)

        if not deng:
            return Response({
                'code':400,
                'msg':"验证码已过期"
            })

        if deng.decode().lower() == wang.lower():
            return Response({
                'code':200,
                'msg':'验证成功'
            })

        return Response({
            'code':400,
            'msg':'验证码错误'
        })



import string
import random
from captcha.image import ImageCaptcha
import redis

# 图片验证码
class TuYan(APIView):
    def get(self,request,uuid):
        # 生成一个随机码

        wang = ''.join(random.sample(string.ascii_letters + string.digits,4))

        # 生成图片序列

        img = ImageCaptcha()

        # 生成字节码

        dada = img.generate(wang)


        # 将随机码存储到
        redisw = redis.Redis(host='localhost',port=6379,password='123321')

        redisw.set(uuid,wang,ex=60 * 5)

        return HttpResponse(dada,content_type='image/png')


    def post(self,request,uuid):
        # 接收前端数据

        shou = request.data.get('前端输入的验证妈')

        redisw = redis.Redis(host='localhost', port=6379, password='123321')

        wang = redisw.get(uuid)

        # 判断是否过期

        if not wang:
            return Response({
                'code':400,
                'msg':'验证码已过期'
            })


        # 判断是否正确
        if wang.decode().lower() == shou.lower():
            return Response({
                'code':200,
                'msg':'验证cehngg'
            })

        return Response({
            'code':400,
            'msg':'验证失败'
        })


# 登入
from myapp.models import User
from django.contrib.auth.hashers import check_password
import time
from django.conf import settings
class Deng(APIView):
    def post(self,request):
        # 接收前端数据

        name = request.data.get('账号')
        password = request.data.get('密码')


        # 验证账号是否正确

        zhang = User.objects.filter(Q(username=name) | Q(mobile=name)).first()

        if not zhang:
            return Response({
                'code':400,
                'msg':'用户名错误'
            })

        # 判断密码是否正确
        if check_password(password,zhang.password):
            token = self.wangda(zhang)
            return Response({
                'code':200,
                'msg':'登入成功',
                'token':token,
                'username':zhang.username,
            })

        return Response({
            'code':400,
            'msg':'密码错误'
        })

    @staticmethod
    def wangda(user):
        '''

        :param user:
        :return:
        '''
        wang = {
            'id':user.id,
            'username':user.username,
            'exe':time.time() + 999
        }

        jwt.encode(wang,key=settings.SECRET_KEY,algorithm='HS265')





class Zhu(APIView):
    def post(self,request):
        # 接收前端数据

        name = request.data.get('账号')
        password = request.data.get('密码')
        shoujih = request.data.get('手机号')

        # 判断手机号和账号有没有重复

        if User.objects.filter(username=name):
            return Response({
                'code':400,
                'msg':'账号重复'
            })

        if User.objects.filter(mobile=shoujih):
            return Response({
                'code':400,
                'msg':'手机号重复'
            })


        User.objects.create_user(username=name,password=password,mobile=shoujih)

        return Response({
            'code':200,
            'msg':'注册成功'
        })



import random
import string
import redis
from captcha.image import ImageCaptcha
# 图片验证码

class DengDa(APIView):
    def get(self,request,uuid):
        # 生成一个随机码

        sui = ''.join(random.sample(string.ascii_letters + string.digits,4))

        # 生成图片序列
        img = ImageCaptcha()

        zi = img.generate(sui)


        # 存储redis

        rediss = redis.Redis(host='localhost',port=6379,password='123321')

        rediss.set(uuid,sui,ex=60 * 5)

        return HttpResponse(zi,content_type='image/png')

    def post(self,request,uuid):
        # 接收前端数据
        yanzheng = request.data.get("前端验证码")

        rediss = redis.Redis(host='localhost', port=6379, password='123321')
        wang = rediss.get(uuid)


        if not wang:
            return Response({
                'code':400,
                'msg':'验证码过期'
            })

        if wang.decode().lower() == yanzheng.lower():
            return Response({
                'code':200,
                'msg':'验证码成功'
            })
        return Response({
            'code':400,
            'msg':'验证码错误'
        })





# 图片验证码
import random
import string
from captcha.image import ImageCaptcha
import redis
class XiaoDa(APIView):
    def get(self,request,uuid):
        # 生成一个随机数

        sui = ''.join(random.sample(string.ascii_letters + string,4))

        # 生成图片序列
        img = ImageCaptcha()

        # 生成字节码
        wang = img.generate(sui)

        # 存储redis
        rediss = redis.Redis(host='localhost',port=6379,password='123321')

        rediss.set(uuid,sui,ex=60 * 5)

        return HttpResponse(wang,content_type='image/png')

    def post(self,request,uuid):
        # 接受前端数据

        yanzheng = request.data.get('前端验证码')

        rediss = redis.Redis(host='localhost', port=6379, password='123321')

        xiao = rediss.get(uuid)

        if not xiao:
            return Response({
                'code':200,
                'msg':'验证码过期'
            })

        if xiao.decode().lower() == yanzheng.lower():
            return Response({
                'code':200,
                'msg':'验证正确'
            })

        return Response({
            'code':400,
            'msg':'验证码错误'
        })



# 登入
from django.contrib.auth.hashers import check_password

class Dengda(APIView):
    def post(self,request):
        # 接受前端数据
        name = request.data.get('用户名')
        password = request.data.get('密码')

        # 判断手机号是否正确

        user = User.objects.filter(username=name).first()

        if not user:
            return Response({
                'code':400,
                'msg':'用户名错误'
            })

        if check_password(password,user.password):
            token = self.xiaoda(user)
            return Response({
                'code':200,
                'msg':'登入成功',
                'token':token,
                'username':user.username,
            })

        return Response({
            'code':400,
            'msg':'密码错误'
        })

    @staticmethod
    def xiaoda(user):
        '''

        :param user:
        :return:
        '''

        wang = {
            'id':user.id,
            'username':user.username,
            'exe': time.time() + 999
        }

        xiao = jwt.encode(wang,key=settings.SECRET_KEY,algorithm='HS256')
        return xiao


from collects.models import GoodCollection
from myapp.models import User
from django.conf import settings
# 收藏
class ShouCang(APIView):
    def post(self,request):
        # 接受前端数据
        # 商品id
        good_id = request.data.get('商品id')

        # 用户信息
        token = request.headers.get('Authorization')

        try:
            wang = jwt.decode(token,key=settings.SECRET_KEY,algorithms=['HS256'])
        except Exception as e:
            print('错误信息',e)
            return Response({
                'code':400,
                'msg':'未认证'
            })

        uid = wang.get('id')

        # 商品是否第一次收藏

        deng = GoodCollection.objects.filter(user_id=uid,good_id=good_id)
        if deng:
            return Response({
                'code':400,
                'msg':'该商品已收藏'
            })

        GoodCollection.objects.create(user_id=uid,good_id=good_id)

        return Response({
            'code':200,
            'msg':'商品收藏成功'
        })




    def get(self,request):

        # 接受前端用户信息
        token = request.headers.get('Authorization')

        try:
            wang = jwt.decode(token,key=settings.SECRET_KEY,algorithms=['HS256'])

        except Exception as e:
            print('错误信息',e)
            return Response({
                'code':400,
                'msg':'未认证'
            })
        print('解码之后',wang)
        uid = wang.get('id')


        xiao = GoodCollection.objects.filter(user_id=uid)

        list1 = []
        for i in xiao:
            shen = i.good
            list1.append(shen)


        list2 = []

        for i in list1:
            da = {
                'id' : i.id,
                'sku_name':i.sku_name,
                'price' :i.price,
                'selling_price':i.selling_price,
                'img':i.img,
                'title':i.title,
                'instruction':i.instruction,
                'count':i.count,
                'stock':i.stock,
                'cate':i.cate.id,
                'online':i.online,
            }
            list2.append(da)


        return Response({
            'code':200,
            'msg':'加载成功',
            'data':list2,

        })





































